<template>
  <div v-loading="laodEditDataloading" :class="{'mobile-create': showMobilePage}" class="create-resource create-page-container">
    <el-form
      ref="editResouceForm"
      :model="editResouceForm"
      :rules="editResouceRules"
      :disabled="false"
      :label-position="formAlign"
      label-width="100px"
      class="lineHeight32">
      <div class="resource-top">
        <Title :title="'平台选择'" font-size="16px" >
          <div :style="showMobilePage?'width:200px;margin-left:24px;':''" class="tip">{{ !isEdit?'注意：创建成功后平台不可以进行修改，如要修改平台请新建资源':'当前资源所属平台无法变更，如要修改平台请新建资源' }}</div>
        </Title>
        <img v-if="isEdit" :src="accountStatusImg" class="contract-icon" alt="">
        <el-row :class="{'flex-wrap':showMobilePage, 'ordertype-box': !showMobilePage}" type="flex" class="flex-center">
          <el-col :span="24">
            <el-form-item key="platformType" prop="platformType" label="平台" style="margin:17px 0 0 0">
              <div class="label-item">
                <selectWithoutHttp
                  v-if="!isEdit"
                  v-model="editResouceForm.platformType"
                  :list-data="platformList"
                  :disabled="platformTypeDisabled"
                  filterable
                  class="width240"
                  style="margin-right: 10px;"
                  placeholder="请选择平台"
                  @change="platformTypeChange"
                />
                <template v-else>
                  <platformIcon :data="editResouceForm.platformTypeName" />
                  <span style="margin-right: 10px;">{{ editResouceForm.platformTypeName }}</span>
                </template>
                <el-checkbox
                  v-model="editResouceForm.autoPick"
                  @change="autoPickChange">{{ platformDesc }}</el-checkbox>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <Title :title="'资源编辑'" font-size="16px" style="margin-bottom:16px">
        <div :style="showMobilePage?'width:200px;margin-left:24px;':''" class="tip">说明：以下内容为新建资源基础信息(*为必填项)，提交后可以填写更多信息</div>
      </Title>
      <div class="resource-edit">
        <el-row type="flex" class="response-create-row">
          <el-col :span="12" class="responsive-col-lg-8 rel">
            <el-form-item
              :class="showMobilePage && 'mobile-el-item'"
              prop="resourceName"
              label="账号">
              <div class="flex-center">
                <el-input
                  v-model.trim="editResouceForm.resourceName"
                  :disabled="resourceNameDisable"
                  :maxlength="50"
                  :type="'text'"
                  name="resourceName"
                  placeholder="请输入"
                  class="width240" />
                <tipIcon content="提交后账号名称前后的空格会自动去除" class="warn-icon" style="margin-top:0;"/>
              </div>
            </el-form-item>
            <div
              v-if="hasResourceType === 1 && editResouceForm.resourceName"
              :class="{'flex-wrap':showMobilePage}"
              class="quick-tip">
              平台已登记类似账号，建议确认后再新建，<el-link type="primary" @click.native="quickFindResource">快速查看</el-link>
            </div>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8 rel">
            <div>
              <el-form-item
                :class="showMobilePage && 'mobile-el-item'"
                prop="resourceId"
                label="账号ID">
                <el-input
                  v-model.trim="editResouceForm.resourceId"
                  :disabled="resourceIdDisable"
                  :maxlength="500"
                  :type="'text'"
                  class="width240"
                  placeholder="请输入唯一标识ID"
                  name="resourceId"
                  clearable />
              </el-form-item>
            </div>
            <div v-if="hasResourceType === 2 && editResouceForm.resourceId" :class="{'flex-wrap':showMobilePage}" class="quick-tip">平台已登记该账号ID，无法重复创建，<el-link type="primary" @click.native="quickFindResource">快速查看</el-link></div>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8 rel">
            <el-form-item
              :class="showMobilePage && 'mobile-el-item'"
              :rules="resourceLinkRules"
              prop="resourceLink"
              label="主页链接">
              <div class="flex-center">
                <el-input
                  v-model.trim="editResouceForm.resourceLink"
                  :disabled="resourceLinkDisable"
                  :maxlength="500"
                  :type="'text'"
                  name="resourceLink"
                  clearable
                  placeholder="请输入"
                  class="width240" />
                <tipIcon :content="linkDisable && hasChoosePlatformType?'平台为微信视频号时链接无需填写':'请输入账号的主页链接<br>示例：https://space.bilibili.com/123456'" class="warn-icon" style="margin-top:0;" use-html/>
              </div>
            </el-form-item>
            <div v-if="hasResourceType === 3 && editResouceForm.resourceLink" class="quick-tip">平台已登记该链接，无法重复创建，<el-link type="primary" @click.native="quickFindResource">快速查看</el-link></div>
            <div v-else-if="!isLinkMatch && editResouceForm.resourceLink" class="quick-tip">你输入的链接可能与选择的平台不符</div>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item
              prop="operateMode"
              label="运营模式">
              <el-cascader
                v-model="editResouceForm.operateMode"
                :props="{ emitPath: false }"
                :options="operateModeList"
                :disabled="operateModeDisable"
                popper-class="tag-overflow"
                clearable
                filterable
                name="operateMode"
                class="width240"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" class="response-create-row">
          <el-col :span="12" :class="{'label-collapse-global': accountOperationRequired}" class="responsive-col-lg-8">
            <el-form-item
              :rules="accountOperationRules"
              :class="{'accountOperation': accountOperationDisable}"
              prop="accountOperation"
              label="其他运营人员">
              <div class="flex-center">
                <select-with-user-load
                  v-model="editResouceForm.accountOperation"
                  :disabled="accountOperationDisable"
                  :hide-select-list="defaultUserList || []"
                  :clearable="true"
                  :multiple="true"
                  :collapse-tags="false"
                  class="width240"
                  show-check-user
                  placeholder="请选择"
                  filterable
                />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item
              :rules="attributionMatrixRules"
              label="所属经营体"
              prop="attributionMatrix">
              <el-cascader
                v-model="editResouceForm.attributionMatrix"
                :show-all-levels="false"
                :options="deptTreeList"
                :disabled="attributionMatrixDisable"
                :props="{
                  emitPath:false,
                  value: 'id',
                  label: 'name',
                  checkStrictly: true,
                  multiple: false,
                }"
                popper-class="tag-overflow"
                placeholder="请选择所属经营体"
                size="small"
                collapse-tags
                filterable
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item
              :rules="cooperationObjRules"
              prop="cooperation"
              label="合作运营方">
              <div class="flex-center">
                <select-with-user-load
                  ref="mengliSuppliers"
                  v-model="editResouceForm.cooperationObj"
                  :disabled="cooperationObjDisable"
                  :loadmore-method="getSupplier({ onlyChannel: true })"
                  :hide-select-list="editResouceForm.cooperationObj ? [editResouceForm.cooperationObj] : []"
                  :clearable="true"
                  :key-name="'supplierName'"
                  :add-new="true"
                  placeholder="请选择"
                  value-type="object"
                  label-name="supplierName"
                  extend-class="image"
                  filterable
                  class="width240"
                  collapse-tags
                  @change="suppliersChange"
                  @clear="clearSupplier"
                  @addNewClick="goCreateSupplier"
                />
                <tipIcon content="飞博供应商" class="warn-icon" style="margin-top:0;"/>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="供应商类型" prop="supplierType">
              <el-select
                v-if="editResouceForm.cooperation"
                v-model="editResouceForm.supplierType"
                disabled
                clearable
                placeholder="--"
                size="small"
                class="width240"
              >
                <el-option
                  v-for="(select, index) in supplierType"
                  :key="index"
                  :label="select.value"
                  :value="select.id" />
              </el-select>
              <div v-else :style="showMobilePage?'width:208px':''" class="mock-input">--</div>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="是否挂靠" prop="microTask">
              <div class="flex-center">
                <el-select
                  v-model="editResouceForm.microTask"
                  :disabled="microTaskDisable"
                  value-key="id"
                  clearable
                  size="small"
                  class="width240"
                >
                  <el-option
                    v-for="(select, index) in microTaskData"
                    :key="index"
                    :label="select.value"
                    :value="select.id" />
                </el-select>
                <tipIcon v-if="microTaskTip" :content="microTaskTip" class="warn-icon" style="margin-top:0;"/>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <!-- 协作部门暂时隐藏 -->
            <el-form-item label="协作部门" prop="cooperationDepartment">
              <filter-cascader
                v-model="cooperationDepartment"
                :options="deptTreeList"
                :disabled="!hasChoosePlatformType"
                popper-class="tag-overflow"
                placeholder="请选择协作部门"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="标签" prop="tag">
              <div class="flex-center">
                <TagSelect ref="tagRef" v-model="editResouceForm.tag" :collapse-tags="false" :module-type="TAG_MODULES.RESOURCE" :platform="editResouceForm.platformType" :need-plat-form-params="true" limit class="width240"/>
                <tipIcon content="标签最多可选择3个" class="ml5"/>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="内容标签" prop="additionalKey.tagRemark">
              <el-input v-model="editResouceForm.additionalKey.tagRemark" placeholder="请输入" class="width240" type="text" maxlength="200"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="跟进人" prop="followUsers">
              <div class="flex-center">
                <selectWithUserLoad
                  ref="proposerRef"
                  v-model="editResouceForm.followUsers"
                  :hide-select-list="editResouceForm.followUsers || []"
                  :show-check-user="true"
                  :value-type="'object'"
                  class="width240"
                  key-name="id"
                  label-name="userName"
                  multiple
                  filterable/>
                <tipIcon content="跟进人拥有该账号自动生成结算单的权限" class="warn-icon" style="margin-top:0;"/>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="responsive-col-lg-8">
            <el-form-item label="是否新号" prop="isNewAccount">
              <selectWithoutHttp
                v-model="editResouceForm.additionalKey.isNewAccount"
                :list-data="newAccountOptions"
                clearable
                class="width240"
                style="margin-right: 10px;"
                placeholder="请选择"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
    <!-- 创建信息 -->
    <CreateInfo
      v-if="isEdit"
      :show-mobile-page="showMobilePage"
      :info="editResouceForm"
    />
    <fixed-pagination>
      <div class="center">
        <el-button :loading="loading" class="mobile-btn-flex flex-center" type="primary" size="small" @click="toSave('editResouceForm')">
          <div class="flex-center">
            保存
            <tipIcon v-if="fromSignUp && !loading" is-btn-tip class="ml5" content="同步完成后，请返回签约内审进行后续操作"/>
          </div>
        </el-button>
        <el-button type="info" class="back-btn cancel-btn-style" size="small" plain @click="toBack">取消</el-button>
      </div>
    </fixed-pagination>
    <createSignAccountInfo
      ref="createSignAccountInfo"
      :platform-list="platformList"
      :is-signed="isSigned"
      :is-edit="isEdit"
      :from-sign-up="fromSignUp"
      v-model="editResouceForm"
      @setOldData="setOldData"
      @updateFollowUsers="updateFollowUsers"/>
  </div>
</template>
<script>
import CreateInfo from './model/createInfo';
import createSignAccountInfo from './model/createSignAccountInfo';
import { getPlatformTypeName } from './resourceData';
import { editResource, getResouceInfo, addResource } from '@/api/resource';
import { signUpDetail } from '@/api/signUp';
import { fieldsMapping } from '@/utils/signUpMappingResource';
import { paramsRangeFormat } from '@/utils/paramsFormat';
import { getDeptName } from '@/utils';
import { getExplorer } from '@/utils/tools';
import createMixins from './model/createMixins';
import mobileCreate from '@/mixins/mobileCreate';
export default {
  components: {
    CreateInfo,
    createSignAccountInfo
  },
  mixins: [mobileCreate, createMixins],
  data() {
    return {
      editResouceForm: {
        resourceType: 0,
        resourceName: '',
        resourceId: '',
        resourceLink: '', // 链接 v2.0.2 新增 time:2019.05.29
        operateMode: [], // 运营模式 v2.0.2 新增 time:2019.05.29
        cooperation: '', // 合作运营方 v2.0.2 新增 time:2019.05.29
        attributionMatrix: '', // 所属经营体
        accountOperation: [], // 其他运营人员
        cooperationDepartment: [],
        microTask: '',
        platformType: '',
        tag: [],
        supplierType: '',
        cooperationObj: null,
        autoPick: false, // 是否开启自动采集
        followUsers: [],
        isNewAccount: 0,
        tagRemark: '',
        platformCategory: '',
        additionalKey: { // 详见rap文档
          articlesPrice: {},
          costPrice: {
            starMapTwenty: {}, // 【抖音】星图报价1-20s
            starMapSixty: {}, // 【抖音】星图报价20-60s
            starMapAboveSixty: {}, // 【抖音】星图报价60s以上
            contentCollectionPrice: {}, // 【抖音】内容合集单坑位报价
            customVideo: {}, // 【B站】定制视频
            implantationVideo: {}, // 【B站】植入视频
            publishTrends: {}, // 【B站】直发动态
            forwardTrends: {}, // 【B站】转发动态
            publish: {}, // 【微博】非原创直发
            forward: {}, // 【微博】非原创转发
            originalContent: {}, // 【微博】原创图文发布
            originalVideo: {} // 【微博】原创视频发布
          },
          monthReportPrice: {}, // 本月报备价(即本月平台价格)
          nextMonthReportPrice: {}, // 次月报备价(即次月平台价格)
          monthNotReportPrice: {}, // 本月非报备价
          nextMonthNotReportPrice: {}, // 次月非报备价
          monthReportPriceCost: {
            imageTextPrice: {},
            videoPrice: {}
          },
          monthNotReportPriceCost: {
            imageTextPrice: {},
            videoPrice: {}
          },
          nextMonthReportPriceCost: {
            imageTextPrice: {},
            videoPrice: {}
          },
          nextMonthNotReportPriceCost: {
            imageTextPrice: {},
            videoPrice: {}
          },
          microTaskCost: {
            publish: {},
            forward: {}
          },
          tagRemark: '',
          isNewAccount: '',
          selectionStatus: '',
          cooperationOption: '',
          sex: null,
          city: '',
          journalStatus: '',
          publicationTime: '',
          shortVideoPrice: '',
          signGroups: '',
          operatorId: [],
          operator: [],
          executeBrokerId: [],
          followContractBrokerId: [],
          journalNode: '',
          isFrameOut: '',
          isVoiceAnchor: '',
          masterFit: '',
          orderRequest: '',
          recommendRank: '',
          freeAuth: {
            isConfirm: true,
            cost: ''
          },
          otherFreePlatform: {
            isConfirm: true,
            cost: ''
          },
          hasShopPrice: {
            isConfirm: true,
            cost: ''
          },
          addBrand: {
            isConfirm: true,
            cost: ''
          },
          retentionAllowed: {
            isConfirm: true,
            timeLimit: ''
          },
          allowCar: {
            isConfirm: true,
            cost: ''
          },
          carCommission: {
            isConfirm: true,
            cost: ''
          }
        },
        moreAccountInfo: {
          fansNum: null,
          averageReadNum: '',
          exposure: '',
          averagePlayNum: '',
          averageInteractionNum: '',
          averageLikeNum: ''
        },
        morePriceInfo: {
          profitSharingRemark: '',
          profitSharingRatio: '',
          guaranteeRemark: '',
          guaranteePrice: '',
          priceTime: []
        },
        journalKey: {
          dynamicKey: []
        },
        moreJournalKey: {
          dynamicKey: []
        },
        costInfoKey: {
          dynamicKey: []
        },
        handoverKey: {
          dynamicKey: []
        },
        otherInfo: {
          payMethod: '',
          mainName: '',
          taxPoint: '',
          actualTaxPoint: '',
          organization: '',
          businessContact: ''
        }
      }
    };
  },
  computed: {
    rangeKeyArr() {
      return [
        { attr: 'cooperationTime', start: 'cooperationStart', end: 'cooperationEnd' },
        { attr: 'signDate', start: 'signStartDate', end: 'signEndDate' }
      ];
    },
    fromSignUp() {
      return Number(this.$route.query.fromSignUp) === 1;
    },
    isInFeiShu() {
      return getExplorer() === 'Feishu';
    }
  },
  // 自营，合作运营，独家代理，其他
  created() {
    this.load();
    // 用于监听新建合作运营方的事件
    window.addEventListener('storage', (e) => {
      this.getSupplier();
      localStorage.removeItem('freshResource');
    });
    this.currentOrigin = window.navigator.userAgent || getExplorer() || 'PC';
  },
  beforeRouteEnter(to, from, next) {
    if (from.name === 'detailResource') {
      to.meta.isDetail = true;
    } else {
      to.meta.isDetail = false;
    }
    next();
  },
  methods: {
    async load() {
      this.resourceId = Number(this.$route.params.resourceId) || '';
      // 获取所属平台
      this.getPlatformList();
      this.getSupplier();
      if (this.isEdit) {
        this.resourceInfo();
      } else {
        if (this.fromSignUp) {
          this.setDataFormSignUp(true);
        }
      }
      // 部门
      await this.queryDeptTreeList(this.isEdit);
      // 运营模式
      await this.getOperateoptions();
    },
    resourceInfo() {
      this.laodEditDataloading = true;
      this.fromSignAndFinished = false;
      getResouceInfo(this.resourceId).then(({ code, message, data }) => {
        this.laodEditDataloading = false;
        // v2.0.2 不允许切换类型，默认内品，所以修改成 resourceType = 0 。time: 2020-5-29
        data.resourceType = 0;

        if (data.operateMode && Array.isArray(data.operateMode)) {
          data.operateMode = data.operateMode[data.operateMode.length - 1];
        }
        const accountOperation = data.accountOperation;
        if (accountOperation && accountOperation.length) {
          data.accountOperation = accountOperation.map(i => {
            this.defaultUserList.push({
              id: i.id,
              userName: i.value
            });
            return i.id;
          });
        }
        if (data.cooperationDepartment) {
          this.cooperationDepartment = data.cooperationDepartment.map(i => i.id);
        }
        if (!data.resourceLink) data.resourceLink = '';
        if (!data.operateMode) data.operateMode = '';
        if (!data.cooperation) data.cooperation = '';
        this.historyAccountOperation = data.historyAccountOperation || [];
        if (!this.isNodeIdExistInTree(data.attributionMatrix, this.deptTreeList)) {
          data.attributionMatrix = '';
        }
        // 签约号相关信息处理
        this.handleSignData(data);
        this.editResouceForm = data;
        if (data.followUsers && data.followUsers.length > 0) {
          data.followUsers = data.followUsers.map(item => {
            item.userName = item.name;
            return item;
          });
        }
        this.$set(this.editResouceForm, 'followUsers', data.followUsers || []);
        if (data.channelId) {
          this.editResouceForm.cooperationObj = {};
          this.editResouceForm.cooperationObj.supplierName = data.cooperation;
          this.editResouceForm.cooperationObj.supplierType = data.supplierType;
          this.editResouceForm.cooperationObj.supplierId = data.channelId;
        }
        // 编辑时切换合作模式回填默认值
        this.editDefaultData = {
          'accountOperation': data.accountOperation,
          'attributionMatrix': data.attributionMatrix,
          'cooperationObj': this.editResouceForm.cooperationObj,
          'supplierType': data.supplierType
        };
        this.setDataFormSignUp();
      }).catch(err => {
        console.log(err);
      });
    },
    async handleSignData(formData) {
      // 历史数据处理
      const additionalKeys = Object.keys(this.editResouceForm.additionalKey);
      additionalKeys.forEach(key => {
        const outValue = formData.additionalKey[key];
        if (!outValue && outValue !== 0 && outValue !== false) {
          this.$set(formData.additionalKey, key, this.editResouceForm.additionalKey[key]);
        }
        if (Object.prototype.toString.call(formData.additionalKey[key]) === '[object Object]') {
          const innerKeys = Object.keys(formData.additionalKey[key]);
          innerKeys.forEach(innerKey => {
            const value = formData.additionalKey[key][innerKey];
            if (!value && value !== 0 && value !== false) {
              this.$set(formData.additionalKey[key], innerKey, this.editResouceForm.additionalKey[key][innerKey]);
            }
          });
        }
      });
      if (!formData.moreAccountInfo) {
        formData.moreAccountInfo = {
          fansNum: null
        };
      }
      const { cooperationStart, cooperationEnd, signStartDate, signEndDate, operatorId } = formData.additionalKey || {};

      formData.additionalKey.signDate = signStartDate ? [signStartDate, signEndDate] : [];
      formData.additionalKey.cooperationTime = cooperationStart ? [cooperationStart, cooperationEnd] : [];

      if (!operatorId)formData.additionalKey.operatorId = [];

      if (!formData.morePriceInfo) {
        formData.morePriceInfo = {
          priceTime: []
        };
      } else {
        const { startTime, endTime } = formData.morePriceInfo.priceTime || {};
        this.$set(formData.morePriceInfo, 'priceTime', []);
        if (startTime && endTime) {
          formData.morePriceInfo.priceTime = [startTime, endTime];
        }
      }
      formData.morePriceInfo.profitSharingRatio !== null ? (formData.morePriceInfo.profitSharingRatio += '') : '';
      if (!formData.otherInfo) {
        formData.otherInfo = {
        };
      }
      const keys = ['journalKey', 'moreJournalKey', 'costInfoKey', 'handoverKey'];
      keys.forEach(key => {
        if (!formData[key]) {
          formData[key] = {
            dynamicKey: []
          };
        } else {
          if (!formData[key].dynamicKey)formData[key].dynamicKey = [];
        }
      });
      await this.$refs.createSignAccountInfo.getDynamic(formData);
    },
    // 签约资源账号跳转数据
    setDataFormSignUp(create = false) {
      const { signUpId, accountId, fromSignUp } = this.$route.query;
      if (!fromSignUp) return;
      if (!signUpId && signUpId !== 0) return;
      signUpDetail(signUpId).then(res => {
        if (res.code === 200) {
          const list = res.data && res.data.accountsInfoList || [];
          res.data.accountsInfoList = list.filter(i => i.id === Number(accountId));
          this.initAccountData(res.data, signUpId, create);
        }
      }).catch((err) => {
        console.log(err);
      });
    },
    // 同步签约内审账号值
    async initAccountData(data, signUpId, create = false) {
      const isFinished = data.workFlowStatus === 4;
      Object.keys(fieldsMapping).forEach(key => {
        // 仅完成才同步的值
        const finishedKeys = ['accountsInfoList[0].contractInfo.legalCode', 'accountsInfoList[0].contractInfo.autoRenewal', 'signLink'];
        if (!isFinished && finishedKeys.includes(key)) return;

        let value = _.get(data, key);
        if (key === 'accountsInfoList[0].priceInfo.profitSharingRatio') { // 分成比例
          value !== null ? (value += '') : '';
        } else if (key === 'channelName') {
          const cooperationObj = {
            supplierName: data.channelName,
            supplierType: data.supplierType === 1 ? 0 : 1, // 资源这边的供应商类型取反了
            supplierId: data.channelId
          };
          this.$set(this.editResouceForm, 'cooperationObj', cooperationObj);
        } else if (key === 'supplierType') {
          _.set(this.editResouceForm, fieldsMapping[key], value === 1 ? 0 : 1);
          return;
        } else if (key === 'accountsInfoList[0].contractInfo.cooperationDepartment') { // 协作部门
          this.cooperationDepartment = value || [];
        } else if (key === 'signLink') {
          value = {
            id: data.id,
            processId: data.processId,
            sn: data.sn
          };
        } else if (key === 'departmentId') {
          value = getDeptName(value, this.deptTreeList);
        }
        _.set(this.editResouceForm, fieldsMapping[key], value);
      });
      const { signStartDate, signEndDate, signLegal } = this.editResouceForm.additionalKey;
      this.$set(this.editResouceForm.additionalKey, 'signDate', signStartDate ? [signStartDate, signEndDate] : []);
      this.$set(this.editResouceForm, 'signUpIdForSync', Number(signUpId)); // 签约内审同步事件后端判断关联id
      if (isFinished) {
        this.editResouceForm.signUpId = Number(signUpId);
        this.fromSignAndFinished = true;
      }
      if (signLegal && signLegal.id) {
        const { contractEffectStartDate, contractEffectEndDate } = data.accountsInfoList[0].contractList && data.accountsInfoList[0].contractList[0] || {};
        signLegal.validityStart = contractEffectStartDate;
        signLegal.validityEnd = contractEffectEndDate;
      }
      if (create) {
        this.$set(this.editResouceForm.additionalKey, 'operatorId', [this.userInfo.id]);
        this.editResouceForm.additionalKey.operator = [{ id: this.userInfo.id, userName: this.userInfo.userName }];
        await this.$refs.createSignAccountInfo.getDynamic(this.editResouceForm);
      }
      this.syncDynamicField(data);
      this.$nextTick(() => {
        this.initCreate = false;
      });
    },
    syncDynamicField(signInfo = {}) {
      const data = signInfo.accountsInfoList[0];
      // 同步自定义字段：小红书须同步健康状态和蒲公英信用等级字段
      if (getPlatformTypeName(this.editResouceForm.platformType, this.platformList) === '小红书') {
        const syncFieldNames = [{ name: '健康状态', module: 'accountsInfo', syncModule: 'moreAccountInfo' }, { name: '蒲公英信用等级', module: 'accountsInfo', syncModule: 'moreAccountInfo' }];
        syncFieldNames.forEach(el => {
          const signUpField = data[el.module].dynamicKey && data[el.module].dynamicKey.find(i => i.name === el.name);
          const resourceField = this.editResouceForm[el.syncModule].dynamicKey && this.editResouceForm[el.syncModule].dynamicKey.find(i => i.name === el.name);
          if (signUpField && resourceField) {
            const idx = this.editResouceForm[el.syncModule].dynamicKey.findIndex(i => i.name === el.name);
            const newItem = this.editResouceForm[el.syncModule].dynamicKey[idx];
            const oldItem = signUpField;
            if (newItem.inputType === 1 && oldItem.inputType === 1) {
              let curOldItem = {};
              if (oldItem.options) {
                curOldItem = oldItem.options.find(j => j.value === oldItem.value);
              }
              const curNewItem = newItem.options.find(j => j.value === oldItem.value);
              if (curNewItem && curOldItem.label === curNewItem.label) {
                this.$set(newItem, 'value', oldItem.value);
              } else {
                this.$set(newItem, 'value', '');
              }
            } else if ((newItem.inputType === 1 && oldItem.inputType === 0) || (newItem.inputType === 0 && oldItem.inputType === 1)) {
              this.$set(newItem, 'value', '');
            } else {
              this.$set(newItem, 'value', oldItem.value);
            }
          }
        });
      }
    },
    toSignUpDetail() {
      this.$router.push({
        name: 'signUpDetail',
        query: {
          signUpId: this.$route.query.signUpId,
          processId: this.$route.query.processId,
          fromList: 1
        }
      });
    },
    add(params) {
      addResource(params).then((res) => {
        this.loading = false;
        if (res.code === 200) {
          this.$message.success('添加成功');
          if (this.fromSignUp && this.isInFeiShu && this.$route.query.processId) {
            this.toSignUpDetail();
            return;
          }
          this.$router.push({
            name: 'resource',
            query: { platform: res.data.platformType || '1' }
          });
        } else {
          this.$message.error(res.message);
        }
      }, result => {
        this.loading = false;
      });
    },
    edit(params) {
      if (!this.fromSignAndFinished) delete params.signUpId;
      // 判断是否修改,未修改不调用接口
      this.editResouceForm.cooperationDepartment = params.cooperationDepartment.sort(function(a, b) { return a - b; });
      const notModify = JSON.stringify(this.oldData) === JSON.stringify(this.editResouceForm);
      if (notModify && !this.editResouceForm.dynamicModify) {
        this.toBack();
        return;
      }
      editResource(this.resourceId, params).then(({ data, code, message }) => {
        this.loading = false;
        if (this.platformTypeName) this.editResouceForm.platformTypeName = this.platformTypeName;
        if (this.attributionMatrixName) this.editResouceForm.attributionMatrixName = this.attributionMatrixName;
        localStorage.setItem('isSuccess', true);
        localStorage.setItem('changeData', JSON.stringify(this.editResouceForm));
        this.$message.success('修改成功');
        if (this.fromSignUp && this.$route.query.processId && this.isInFeiShu) {
          this.toSignUpDetail();
          return;
        }
        if (this.$route.meta.isDetail) {
          this.$router.push({
            name: 'detailResource',
            params: {
              resourceId: this.resourceId,
              versionNum: data.versionNum
            }
          });
        } else {
          this.$router.push({
            name: 'resource',
            query: { platform: data.platformType || '1' }
          });
        }
      }, result => {
        this.loading = false;
      });
    },
    async toSave(formValue) {
      const params = JSON.parse(JSON.stringify(this.editResouceForm));
      this.isSave = true;
      if (params.fansNum) {
        params.fansNum = parseInt(params.fansNum);
      }
      const signInfoValid = await this.$refs['createSignAccountInfo'].validateForm().catch((err) => { console.log(err); });
      if (!signInfoValid) {
        this.$message.warning('请检查信息是否填写完整');
        return;
      }
      if (params.morePriceInfo.priceTime) {
        if (params.morePriceInfo.priceTime.length) {
          params.morePriceInfo.priceTime = {
            startTime: params.morePriceInfo.priceTime[0],
            endTime: params.morePriceInfo.priceTime[1]
          };
        } else {
          params.morePriceInfo.priceTime = {};
        }
      }
      paramsRangeFormat(this.rangeKeyArr, params.additionalKey);
      this.$refs[formValue].validate((valid) => {
        this.isSave = false;
        if (valid) {
          if (params.tag && params.tag.length > 3) {
            this.$message.warning('标签最多可选择3个');
            return;
          }
          params.channelId = params.cooperationObj ? params.cooperationObj.supplierId : null;// 3.0.3编辑时对channelId赋值
          params.cooperationDepartment = this.cooperationDepartment;
          params.historyAccountOperation = this.historyAccountOperation.map(i => i.id);
          if (params.operateMode && !Array.isArray(params.operateMode)) {
            params.operateMode = [params.operateMode];
          }
          if (Array.isArray(params.followUsers)) {
            params.followUsers = params.followUsers.map(item => {
              return item.id;
            }).join();
          }
          this.loading = true;
          if (!this.isEdit) {
            this.add(params);
          } else {
            this.edit(params);
          }
        } else {
          this.$message.warning('请检查信息是否填写完整');
          return false;
        }
      });
    },
    toBack() {
      localStorage.setItem('isSuccess', false);
      localStorage.setItem('changeData', '');
      if (this.$route.meta.isDetail) {
        this.$router.push({
          name: 'detailResource'
        });
      } else {
        this.$router.push({
          name: 'resource'
        });
      }
    }
  }
};
</script>
<style  lang="scss" scoped>
.create-resource {
  padding-top: 16px;
  box-shadow: 2px 4px 10px #DDE1EA;
  & ::v-deep {
    .el-form-item {
      .el-select {
        width: 240px;
      }
      .el-cascader{
        width: 240px;
      }
      .el-input__inner  {
        width: 240px;
        height: 32px;
      }
      .el-textarea__inner {
        height: 64px !important;
      }
      .el-form-item__label {
        color: #666;
        height: 32px;
      }
      .el-radio__label {
        padding-left: 4px;
        font-size: 14px;
      }
    }
  }
  .warn-icon {
    width: 14px;
    height: 14px;
    margin: 8px 0 0 4px;
  }
  .resource-top {
    margin-bottom: 32px;
    position: relative;
    .contract-icon {
      position: absolute;
      right: 20px;
      top: 20px;
      z-index: 10;
      width: 110px;
    }
    .center{
      display: flex;
      align-items: center;
    }
  }
  .quick-tip {
    position: absolute;
    left: 100px;
    top: 35px;
    font-size:12px;
    font-family:PingFangSC-Regular,PingFang SC;
    font-weight:400;
    color:rgba(153,153,153,1);
    line-height:14px;
    white-space: nowrap;
    display: flex;
    align-items: center;
  }
  .width240 {
    width: 240px;
    & ::v-deep {
      .el-input__inner, .el-select {
        width: 240px;
      }
    }
  }
}
.mobile-create {
  .contract-icon {
    width: 70px !important;
  }
}
.flex-wrap {
  flex-wrap: wrap;
  position: relative;
  &.quick-tip {
    left: 94px;
  }
}
.tip {
  font-size:12px;
  font-family:PingFangSC-Regular,PingFang SC;
  font-weight:400;
  color:rgba(153,153,153,1);
  line-height:14px;
  margin-left: 8px;
  margin-top: 4px;
}
.ordertype {
  font-size:14px;
  font-family:PingFangSC-Regular,PingFang SC;
  line-height:14px;
  margin:0 19px 0px 10px;
  color:rgba(153,153,153,1);
}
.label-item {
  display: flex;
  align-items: center;
  font-size: 14px;
  flex-wrap: wrap;
  // margin: 22px 0;
}
.mock-input {
  width: 240px;
  height: 32px;
  padding: 0 8px;
  border: 1px solid #E4E7ED;
  border-radius: 4px;
  color: #C0C4CC;
  background-color: #F5F7FA;
  line-height: 32px;
  font-size: 14px;
  cursor: not-allowed;
}
</style>
<style lang="scss">
.create-resource{
  .el-icon-info:before {
    font-size: 14px;
    color:rgba(153,153,153,1);
  }
  .el-input__suffix {
    line-height: 28px;
  }
  .el-select-dropdown__item {
    max-width: 235px !important;
  }
  .accountOperation{
    .el-select__input{
      cursor: not-allowed;
    }
  }
  .response-create-row {
    display: flex;
    flex-wrap: wrap;
    @media only screen and (min-width: 1490px) {
      .responsive-col-lg-8 {
        width: 33.33333%;
      }
    }
  }
}
</style>
